package cn.zhangchg.leetcode.arrays;

import java.util.Arrays;

public class Search {
    public static void main(String[] args) {
        int[] array = new int[]{1, 4, 3, 7, 5, 6, 7, 2, 10, 2};

        int search = search(array, 7);
        System.out.println(search);
        search = search(array, 12);
        System.out.println(search);
        search = search(array, 1);
        System.out.println(search);
        search = search(array, 5);
        System.out.println(search);
    }

    public static int searchBak(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        return -1;
    }

    public static int search(int[] arr, int target) {
        System.out.println(Arrays.toString(arr));
        sort(arr);
        System.out.println(Arrays.toString(arr));
        return search(arr, target, 0, arr.length - 1);
    }

    private static void sort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[i]) {
                    swap(arr, i, j);
                }
            }
        }
    }

    private static void swap(int[] arr, int j, int i) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static int search(int[] arr, int target, int left, int right) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        if (arr[mid] == target) {
            return mid;
        }
        if (arr[mid] < target) {
            return search(arr, target, mid + 1, right);
        } else {
            return search(arr, target, 0, mid - 1);
        }
    }
}
